<?php
class PackageInclusionController extends CBaseController
{		
	protected $package;
	protected $inclusion;
	protected $validator;
	public function __construct($config=null) 
    { 
      parent::__construct($config);	  
    } 
	
	public function init($tpl)
	{
		parent::init($tpl);
		$this->reqLogin();
		$this->templator->addViewsDir(dirname(__FILE__).'/../views');
		$this->templator->assign('menu','inclusion');
		$this->prepare();
	}
	
	public function prepare()
	{
		if(isset($_GET['id']))
		{
			$id = $_GET['id'];
			$this->package = R::load('travelpackage',$id);
		}
		elseif(isset($_POST['id']))
		{	
			$id = $_POST['id'];
			$this->package = R::load('travelpackage',$id);
		}
		else
		{
			$this->package = R::dispense('travelpackage');
		}
		$this->prepareInclusion();
	}	
	
	public function prepareInclusion()
	{
		if(isset($_GET['inclusion_id']))
		{
			$id = $_GET['inclusion_id'];
			$this->inclusion = R::load('inclusion',$id);
		}
		elseif(isset($_POST['inclusion_id']))
		{	
			$id = $_POST['inclusion_id'];
			$this->inclusion = R::load('inclusion',$id);
		}
		else
		{
			$this->inclusion = R::dispense('inclusion');
		}
	}
	
	public function saveORupdateValidate()
	{
		$this->validator = new FormValidator();
		$this->validator->addValidation("name","req","Please fill in Name");
		return $this->validator->ValidateForm();
	}
	
	public function savePrepare()
	{
		$this->inclusion->name = $_POST['name'];
		$this->inclusion->position = $_POST['position'];
		$this->inclusion->longdesc = $_POST['longdesc'];
	}
		
	
	public function save()
	{
		$this->savePrepare();
		  if($this->saveORupdateValidate())
		  {
			if(isset($this->inclusion->id) && !empty($this->inclusion->id))
				$this->package->ownInclusion[$this->inclusion->id]=$this->inclusion;
			else
				$this->package->ownInclusion[]=$this->inclusion;
			R::store($this->package);
			$this->templator->assign('info','inclusion added sucessfully');
			$this->inclusion = R::dispense('inclusion');
			$this->inclusions();	
		  }
		  else
		  {
			$error_hash = $this->validator->GetErrors();
			$this->templator->assign('validate_errors',$error_hash);
			$this->inclusions();
		  }
			
	}
	
	public function update()
	{
		$this->save();	
	}
	
	public function edit()
	{
		$this->inclusions();	
	}
	
	public function delete()
	{
		R::trash($this->inclusion);
		$this->inclusion = R::dispense('inclusion');
		$this->inclusions();	
	}
	
	public function inclusions()
	{		
		//$assignedInclusion= R::related( $this->package, 'inclusion' );
		$this->templator->assignByRef('package',$this->package);		
		$this->templator->assignByRef('inclusion',$this->inclusion);		
		$this->templator->assign('inclusions',array_merge($this->package->ownInclusion, array()));
		$this->templator->display('inclusion/package_inclusion.html');
	}
	
	
}	